package chat.network.tcp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Message;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.google.gson.Gson;
import com.orm.SugarRecord;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;

import chat.managers.MyNotification;
import chat.network.http.GetRoomMessage;
import chat.network.http.GetUserMessage;
import chat.network.http.Notify;
import emergency.dto.Emergency;
import inter.Delegate;
import inter.ResponseStatus;
import model.*;
/**
 * 接收推送消息
 * Created by Administrator on 2015/12/29.
 */
public class ReceiveThread extends Thread {

    Context context;
    PowerManager.WakeLock wakelock;
    PowerManager.WakeLock part_wakelock;

    OwnUser ownUser;
    {
        List<OwnUser> ownUsers = SugarRecord.listAll(OwnUser.class);
        if (!ownUsers.isEmpty())
        {
            ownUser = ownUsers.get(0);
        }
    }

    public ReceiveThread(Context context) {
        this.context = context;
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK , "reconnect");
        part_wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "keepalive");

    }
    public  transient boolean isStop;
    public  transient  boolean isRunning;
    Socket socket;

    Scanner scanner;
//    PrintWriter printWriter;
    InputStream in;
    OutputStream o;
    // 监听网络是否可用
    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {

                } else {
                    if (!isStop) {
                        System.out.println("断网，关闭连接");
                        setStop(true);
                    }
                }
            }

        }
    };


    // 写回去
    public void writeback(String str) {
        Log.i("时间",System.currentTimeMillis()+"");
        if (o != null && socket.isConnected()) {
            try {
                o.write((str + "\r\n").getBytes("utf-8"));
                o.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void setStop(Boolean stop) {
        isStop = stop;
        this.interrupt();
        Log.i("请求断开连接线程","可能是断网关闭连接线程");

    }

    @Override
    public void run() {
        try {
            registerBroadcast();
            socket = new Socket();
            socket.setTcpNoDelay(true);
            socket.setSoTimeout(90000);
            socket.setOOBInline(true);
            String ip = MyApplication.share().getString(R.string.tcpIp);
            String port = MyApplication.share().getString(R.string.tcpPort);
            try {
                wakelock.acquire();
                socket.connect(new InetSocketAddress(ip, Integer.parseInt(port)), 5000);
                Log.i("连接上了", "socket连接成功");
                isRunning = true;
            } finally {
                wakelock.release();

            }
            in = socket.getInputStream();
            o = socket.getOutputStream();
            scanner = new Scanner(in,"utf-8");
            scanner.useDelimiter("\r\n");
            initSocket();

            while (!isStop) {
                receiveMessage(scanner, o);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出错，停止");
            setStop(true);

        } finally {
            if (socket != null && socket.isConnected()) {
                try {
                    socket.shutdownInput();
                    socket.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (o != null) {
                try {
                    o.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            isRunning = false;
            Log.i("连接线程关闭","连接线程关闭");
            unregisterBroadcast();
        }
    }


    // 反注册网络监听
    private void unregisterBroadcast() {
        if (myNetReceiver != null) {
            context.unregisterReceiver(myNetReceiver);
        }
    }

    // 注册网络监听
    private void registerBroadcast() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(myNetReceiver, mFilter);
    }


    // socket初次建立，初始化连接信息
    private void initSocket() {
       Log.i("初始化socket,用户ID:",ownUser.getUser_ID()+"");
        if (ownUser.getUser_ID() == null) return;
        // 发送用户信息
        String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        imei = imei + context.getPackageName();
        UserInfoAttached info = new UserInfoAttached();
        info.setUser_ID(ownUser.getUser_ID());
        info.setSys_Name("android");
        info.setOs_Version("");
        info.setPushToken("");
        info.setLatitude(0.0);
        info.setLongitude(0.0);
        info.setEquip_Model(Build.MODEL);
        info.setUuid(UUID.nameUUIDFromBytes(imei.getBytes()).toString().replaceAll("-", ""));
//        try {
//            o.write(("bind:"+JSON.toJSONString(info) + "\r\n").getBytes("utf-8"));
//            Log.i("bind","bind:"+JSON.toJSONString(info));
//            o.flush();

//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        Gson gson = new Gson();
        writeback("bind:"+gson.toJson(info));
    }

    private void receiveMessage(Scanner scanner, OutputStream o) throws IOException {
        if (scanner.hasNext())
        {
            String get = scanner.next();
            if (get.length() == 0) setStop(true);
            dealMessage(get,o);
            TimeCheck.share().setChecekedTime();
        }
        else
        {
            setStop(true);
        }

    }


    // 处理收到的消息
    private void dealMessage(String get, OutputStream o) {
        Log.i("收到推送",get);
        // 收到心跳包
        if (get.equals("0"))
        {
            writeback(Notify.PONG);
            return;
        }

        Gson gson = new Gson();
        Notify.UserMessage userMessage =  gson.fromJson(get,Notify.UserMessage.class);
        if (userMessage.getN().equals("5"))
        {

        }
        // 用户消息
        else if (userMessage.getN().equals("8"))
        {
            GetUserMessage getUserMessage = new GetUserMessage();
            getUserMessage.setUser_FromID(userMessage.getID());
            getUserMessage.setUser_ToID(ownUser.getUser_ID());
            getUserMessage.setDelegate(getUserMessageResponse);
            getUserMessage.get();

        }
        // 房间消息
        else if (userMessage.getN().equals("9"))
        {
            GetRoomMessage getRoomMessage = new GetRoomMessage();
            getRoomMessage.setDelegate(getRoomMessageResponse);
            getRoomMessage.setRoom_ID(userMessage.getID());
            getRoomMessage.setUser_ID(ownUser.getUser_ID());
            getRoomMessage.get();
        }

        // 预警信息
        else if (userMessage.getN().equals("999"))
        {
            String data = userMessage.getID();
            Emergency emergency = gson.fromJson(data, Emergency.class);
            StringBuffer sb = new StringBuffer();
            sb.append(emergency.getWatergateName() + "水位超出" + (emergency.getHeightUp() - emergency.getDesignWaterLevel()) + "厘米");
            MyNotification.notifymy(MyApplication.share(), MyNotification.FLAG_EMEGENCY, "危险", sb.toString(), 0);
            model.Emergency emergency1 = new model.Emergency();
            emergency1.setDesignWaterLevel(emergency.getDesignWaterLevel());
            emergency1.setHeightDown(emergency.getHeightDown());
            emergency1.setHeightUp(emergency.getHeightUp());
            emergency1.setMeaTime(emergency.getMeaTime());
            emergency1.setWatergateName(emergency.getWatergateName());
            SugarRecord.save(emergency1);
        }

    }

    // 获取好友消息
    Delegate getUserMessageResponse = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetUserMessage.ResponseUserMessages responseUserMessages = gson.fromJson(response, GetUserMessage.ResponseUserMessages.class);
            if (responseUserMessages.getStatus().equals(ResponseStatus.SUCCESS))
            {
                List<GetUserMessage.UserMsgs> messages = responseUserMessages.getUserMessages_List();
                for(GetUserMessage.UserMsgs u:messages)
                {
                    model.Message message = new model.Message();
                    message.setMessage_Content(u.getMessage_Content());
                    message.setUser_ToID(ownUser.getUser_ID());
                    message.setMessage_Time(u.getMessage_Time());
                    message.setMessage_Type(u.getMessage_Type());
                    message.setUserfromid(u.getUser_FromID());
                    SugarRecord.save(message);
                }

                // 记入未读消息表
                if (!messages.isEmpty())
                {
                    GetUserMessage.UserMsgs m = messages.get(messages.size()-1);
                    List<MessageNotify> messageNotifies = SugarRecord.findWithQuery(MessageNotify.class, "Select * from MessageNotify where nameid = ? and type = ?", m.getUser_FromID(), "8");
                    int num = 0;
                    // 若不存在过往消息
                    if (messageNotifies.isEmpty())
                    {
                        MessageNotify messageNotify = new MessageNotify();
                        messageNotify.setNameid(m.getUser_FromID());
                        messageNotify.setContent(m.getMessage_Content());
                        messageNotify.setRealName(m.getUser_FromUserName());
                        messageNotify.setTime(m.getMessage_Time());
                        messageNotify.setType("8");
                        messageNotify.setUnread(messages.size() + "");
                        SugarRecord.save(messageNotify);
                        num = messages.size();
                    }
                    else
                    {
                        MessageNotify messageNotify = messageNotifies.get(0);
                        messageNotify.setTime(m.getMessage_Time());
                        messageNotify.setContent(m.getMessage_Content());
                        messageNotify.setUnread((Long.parseLong(messageNotify.getUnread()) + messages.size()) + "");
                        SugarRecord.save(messageNotify);
                        num = Integer.parseInt(messageNotify.getUnread()) + messages.size();
                    }

                    // 发送通知栏
                    MyNotification.notifymy(MyApplication.share(),MyNotification.FLAG_SINGLEMESSAGE,m.getUser_FromUserName(),m.getMessage_Content(),num);

                }

                // 发送收到消息通知
                Intent intent = new Intent("com.whu.administrator.ws.userMessage");
                MyApplication.share().sendBroadcast(intent);
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };

    // 获取房间消息
    Delegate getRoomMessageResponse = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetRoomMessage.ResponseRoomMessages responseRoomMessages = gson.fromJson(response, GetRoomMessage.ResponseRoomMessages.class);
            if (responseRoomMessages.getStatus().equals(ResponseStatus.SUCCESS))
            {
                List<GetRoomMessage.RoomMsgs> roomMsgses = responseRoomMessages.getRm_List();
                for(GetRoomMessage.RoomMsgs r:roomMsgses)
                {
                    RoomMessage roomMessage = new RoomMessage();
                    roomMessage.setRoom_Name(r.getRoom_Name());
                    roomMessage.setUser_ID(r.getUser_ID());
                    roomMessage.setRoom_Name(r.getRoom_Name());
                    roomMessage.setUser_RealName(r.getUser_RealName());
                    roomMessage.setRm_Type(r.getRm_Type());
                    roomMessage.setRm_Content(r.getRm_Content());
                    roomMessage.setRm_Time(r.getRm_Time());
                    roomMessage.setRoomid(r.getRoom_ID());
                    SugarRecord.save(roomMessage);
                }

                // 记入未读消息表
                if (!roomMsgses.isEmpty())
                {
                    GetRoomMessage.RoomMsgs roomMsg = roomMsgses.get(roomMsgses.size()-1);
                    List<MessageNotify> messageNotifies = SugarRecord.findWithQuery(MessageNotify.class, "Select * from MessageNotify where nameid = ? and type = ?", roomMsg.getRoom_ID(), "5");

                    int num;
                    // 若不存在过往消息
                    if (messageNotifies.isEmpty())
                    {
                        MessageNotify messageNotify = new MessageNotify();
                        messageNotify.setNameid(roomMsg.getRoom_ID());
                        messageNotify.setContent(roomMsg.getUser_RealName() + ":" + roomMsg.getRm_Content());
                        messageNotify.setRealName(roomMsg.getRoom_Name());
                        messageNotify.setTime(roomMsg.getRm_Time());
                        messageNotify.setType("5");
                        messageNotify.setUnread(roomMsgses.size() + "");
                        SugarRecord.save(messageNotify);
                        num = roomMsgses.size();
                    }
                    else
                    {
                        MessageNotify messageNotify = messageNotifies.get(0);
                        messageNotify.setTime(roomMsg.getRm_Time());
                        messageNotify.setContent(roomMsg.getUser_RealName() + ":" + roomMsg.getRm_Content());
                        messageNotify.setUnread((Long.parseLong(messageNotify.getUnread()) + roomMsgses.size()) + "");
                        SugarRecord.save(messageNotify);
                        num = Integer.parseInt(messageNotify.getUnread()) + roomMsgses.size();
                    }

                    MyNotification.notifymy(MyApplication.share(),MyNotification.FLAG_GROUPMESSAGE,roomMsg.getRoom_Name(),roomMsg.getUser_RealName()+":"+roomMsg.getRm_Content(),num);
                }

                // 发送房间消息通知
                Intent intent = new Intent("com.whu.administrator.ws.RoomMessage");
                MyApplication.share().sendBroadcast(intent);
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };


}
